/* array.c is part of VIP program
 * Written by J. Salvador Arias, 2010
 *      CONICET, INSUE, Instituto Miguel Lillo,
 *      Miguel Lillo 205, S.M. de Tucuman (4000)
 *      Tucuman, Argentina
 *      e-mail: jsalarias@csnat.unt.edu.ar
 *
 * VIP is a free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation and
 * Creative Commons.
 *
 * This file and the VIP program is distributed in the hope
 * that it will be useful, but WITHOUT ANY WARRANTY; without
 * even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * To view a copy of this license, visit
 * http://creativecommons.org/licenses/GPL/2.0/
 * or send a letter to
 * Creative Commons, 171 Second Street, Suite 300,
 * San Francisco, California, 94105, USA.
 */

#include "ghead.h"

INTARRAY* CreateIntArray (SCOUNTER size) {
 INTARRAY* nu;

 nu = (INTARRAY*) g_slice_alloc (sizeof (INTARRAY));
 nu -> max = size;
 nu -> len = 0;
 nu -> data = (SINTEGER*) g_malloc (sizeof (SINTEGER) * size);
 return nu;
}

void DestroyIntArray (INTARRAY* array) {
 g_free (array -> data);
 g_slice_free1 (sizeof (INTARRAY), array);
}

void ShuffleIntArray (INTARRAY* array) {
 SINTEGER temp;
 SCOUNTER i;
 SCOUNTER act;

 for (i = 0; i < array -> len; ++ i) {
   act = g_random_int_range (0, array -> len);
   temp = array -> data [i];
   array -> data [i] = array -> data [act];
   array -> data [act] = temp;
 }
}

SCOUNTER SearchIndexValue (INTARRAY* array, SINTEGER val) {
 SCOUNTER i;
 for (i = 0; i < array -> len; ++ i)
   if (array -> data [i] == val) return i;
 return 0;
}

void CopyPtrArray (GPtrArray* dest, GPtrArray* src) {
 SCOUNTER i;

 for (i = 0; i < src -> len; ++ i)
   g_ptr_array_add (dest, g_ptr_array_index (src, i));
}

void CopyPtrArrayPart (GPtrArray* dest, GPtrArray* src, SCOUNTER start, SCOUNTER end) {
 SCOUNTER i, max;

 max = (end > src -> len) ? src -> len : end;
 for (i = start; i < max; ++ i)
   g_ptr_array_add (dest, g_ptr_array_index (src, i));
}

void ShufflePtrArray (GPtrArray* array) {
 gpointer temp;
 SCOUNTER i;
 SCOUNTER act;

 for (i = 0; i < array -> len; ++ i) {
   act = g_random_int_range (0, array -> len);
   temp = g_ptr_array_index (array, i);
   array -> pdata [i] = array -> pdata [act];
   array -> pdata [act] = temp;
 }
}

void ShuffleSinglePtrArray (GPtrArray* array, SCOUNTER pos) {
 gpointer temp;
 SCOUNTER act;

 if (pos >= array -> len) return;
 act = g_random_int_range (0, array -> len);
 temp = g_ptr_array_index (array, pos);
 array -> pdata [pos] = array -> pdata [act];
 array -> pdata [act] = temp;
}
